package controllers

import (
	"crypto/md5"
	"fmt"
	// "crypto/rand"
	// "encoding/base64"
	"057dg/models"
	"encoding/hex"
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/orm"
	"os"
	"strconv"
	"strings"
	"time"
)

type AccountUserController struct {
	beego.Controller
}

func (this *AccountUserController) Get() {
	this.Layout = "layout/accountUser.html"
	isExit := this.GetString("isExit") == "true"
	if isExit {
		this.Ctx.SetCookie("uid", "", 0, "/")
		this.Ctx.SetCookie("email", "", 0, "/")
		this.Ctx.SetCookie("password", "", 0, "/")
		this.Redirect("/home", 301)
	}
	if !checkAccount(this.Ctx) {
		this.Redirect("/home", 301)
	}
	this.Data["IsLogin"] = checkAccount(this.Ctx)
	this.TplNames = "account/index.html"
}

func (this *AccountUserController) CheckErr(err error) {
	if err != nil {
		fmt.Println(err)
	}
}

func (this *AccountUserController) Resume() {

	this.Layout = "layout/accountUser.html"

	if !checkAccount(this.Ctx) {
		this.Redirect("/home", 301)
	}

	this.Data["IsLogin"] = checkAccount(this.Ctx)

	uid, err := strconv.Atoi(this.Ctx.GetCookie("uid"))
	this.CheckErr(err)
	resume, err := new(models.Resume).FindOneResume(uid)
	this.Data["resume"] = resume

	var WkExperice = map[string]interface{}{}
	err = json.Unmarshal([]byte(resume.WkExperice), &WkExperice)
	CheckError(err)
	this.Data["WkExperice"] = WkExperice

	var EduExperice = map[string]interface{}{}
	err = json.Unmarshal([]byte(resume.EduExperice), &EduExperice)
	CheckError(err)
	this.Data["EduExperice"] = EduExperice

	if this.GetString("dosubmit") == "true" {

		resume.TrueName = this.GetString("name")
		resume.Gender, _ = this.GetInt("sex")
		resume.Age, _ = this.GetInt("age")
		resume.Experience, _ = this.GetInt("experience")
		resume.Mobile = this.GetString("phone")
		resume.Email = this.GetString("email")

		//求职意向
		resume.TargetProvince = this.GetString("expectedProvince")
		resume.TargetCity = this.GetString("expectedCity")
		resume.TargetPosition = this.GetString("expectedJob")
		resume.ExpectedMonthlySalary = this.GetString("expectedSalary")

		//工作经历
		resume.WkIDSArray = strings.Trim(this.GetString("companyTagArray"), " ")
		var WkExperice = map[string]map[string]string{}

		companyUnixDate := strings.Split(resume.WkIDSArray, ",")
		for _, v := range companyUnixDate {
			Experice := map[string]string{}
			Experice["wkCompany"] = this.GetString("wkCompany" + v)
			Experice["wkJob"] = this.GetString("wkJob" + v)
			Experice["wkFrom"] = this.GetString("wkFrom" + v)
			Experice["wkEnd"] = this.GetString("wkEnd" + v)
			WkExperice[v] = Experice
		}
		WkExpericeJson, err := json.Marshal(WkExperice)
		CheckError(err)
		resume.WkExperice = string(WkExpericeJson)

		//教育经历
		resume.EduIDSArray = strings.Trim(this.GetString("eduTagArray"), " ")
		var EduExperice = map[string]interface{}{}

		EduUnixDate := strings.Split(resume.EduIDSArray, ",")
		for _, v := range EduUnixDate {
			eExperice := map[string]string{}
			eExperice["eduSchool"] = this.GetString("eduSchool" + v)
			eExperice["eduDegree"] = this.GetString("eduDegree" + v)
			eExperice["eduMajor"] = this.GetString("eduMajor" + v)
			eExperice["eduFrom"] = this.GetString("eduFrom" + v)
			eExperice["eduEnd"] = this.GetString("eduEnd" + v)
			EduExperice[v] = eExperice
		}
		EduExpericeJson, err := json.Marshal(EduExperice)
		CheckError(err)
		resume.EduExperice = string(EduExpericeJson)

		//项目经历
		resume.ProjectExperice = this.GetString("projectExperience")

		//作品url

		//隐私设置
		Status, err := this.GetInt("state")
		CheckError(err)
		resume.Status = Status

		if num, err := new(models.Resume).UpdateResume(resume); err == nil {
			fmt.Println("NUM1:", num, "err1:", err)
			this.Data["json"] = 200
		} else {
			fmt.Println("NUM2:", num, "err2:", err)
			this.Data["json"] = 100
		}
		this.ServeJson()
		return
	}
	this.TplNames = "account/resume.html"
}

func (this *AccountUserController) Editavatar() {
	this.Data["Website"] = "beego.me"
	this.Data["Email"] = "astaxie@gmail.com"
	this.TplNames = "account/profile_edit_avatar.html"
}

func (this *AccountUserController) UploadChangeHead() {
	f, h, _ := this.GetFile("myfiles") //获取上传的文件

	path_name := ""
	path_dir := "static/" + time.Now().Format("20060102") + "/temp/"
	if MakeDir(path_dir) {
		filenameArr := strings.Split(h.Filename, ".")
		path_name = path_dir + GetMd5String(strconv.FormatInt(time.Now().Unix(), 10)+string(filenameArr[0])) + "." + string(filenameArr[1])
	} else {
		fmt.Println("创建目录不成功")
		return
	}
	f.Close()                             // 关闭上传的文件，不然的话会出现临时文件不能清除的情况
	this.SaveToFile("myfiles", path_name) //存文件    WaterMark(path)    //给文件加水印
	this.Data["json"] = map[string]string{"sheight": "200", "state": "2", "swidth": "180", "url": "http://localhost:8080/" + path_name}
	// this.TplNames = "account/uploadChangeHead.html"
	this.ServeJson()
}

func (this *AccountUserController) UploadTrueHead() {
	headImgSrc := this.GetString("headImgSrc")
	var JSONRE = map[string]interface{}{}
	JSONRE["STATE"] = 200
	JSONRE["imageInfo"] = map[string]string{"sheight": "200", "swidth": "180", "url": headImgSrc}
	this.Data["json"] = JSONRE
	// this.TplNames = "account/uploadChangeHead.html"
	this.ServeJson()
}

func (this *AccountUserController) Company() {
	this.Layout = "layout/accountUser.html"
	this.Data["Website"] = "beego.me"
	this.Data["Email"] = "astaxie@gmail.com"
	this.TplNames = "account/company.html"
}

func (this *AccountUserController) EditPwd() {
	this.Layout = "layout/accountUser.html"
	this.Data["isFlag"] = 1
	o := orm.NewOrm()
	uid, _ := strconv.Atoi(this.Ctx.GetCookie("uid"))
	user := &models.User{Id: uid}
	// fmt.Println(GetMd5String("SUCCESS198"))
	if dosubmit := this.GetString("dosubmit"); dosubmit == "true" {
		opwd := this.GetString("opwd")
		fmt.Println(opwd)
		fmt.Println(GetMd5String(opwd))
		fmt.Println(this.Ctx.GetCookie("password"))

		if GetMd5String(opwd) != this.Ctx.GetCookie("password") {
			fmt.Println("原密码不对")
			this.Redirect("/acompany/company", 301)
			return
		}
		npwd1 := this.GetString("npwd1")
		npwd2 := this.GetString("npwd2")
		if npwd1 != npwd2 {
			fmt.Println("两次输入不一致")
			this.Redirect("/acompany/company", 301)
			return
		}
		user.PassWord = GetMd5String(npwd1)
		if num, err := o.Update(user, "PassWord"); err == nil {
			fmt.Println(num)
			this.Redirect("/acompany/company", 301)
			return
		}
	}
	this.TplNames = "account/editpwd.html"
}

func MakeDir(path string) bool {
	_, err := os.Stat(path)
	if err != nil {
		err = os.MkdirAll(path, 0666)
		CheckError(err)
		MakeDir(path)
	}
	return true
}

// func UploadFile(Req *http.Request) {
// 	formfile, handle, err := Req.FormFile("file")
// 	defer formfile.Close()
// 	CheckError(err)

// 	path_name := ""
// 	path_dir := "./static/" + time.Now().Format("20060102") + "/"
// 	if MakeDir(path_dir) {
// 		filenameArr := strings.Split(handle.Filename, ".")
// 		path_name = path_dir + GetMd5String(strconv.FormatInt(time.Now().Unix(), 10)+string(filenameArr[0])) + "." + string(filenameArr[1])
// 	} else {
// 		fmt.Println("创建目录不成功")
// 		return
// 	}

// 	f, err := os.OpenFile(path_name, os.O_CREATE, 0666)
// 	defer f.Close()
// 	CheckError(err)
// 	_, err = io.Copy(f, formfile)
// 	CheckError(err)
// 	JieXieCells(f)
// }

//获得md5
func GetMd5String(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	return hex.EncodeToString(h.Sum(nil))
}

func CheckError(err error) {
	if err != nil {
		fmt.Println(err)
	}
}

//验证是否登录
func checkAccount(ct *context.Context) bool {
	ck, err := ct.Request.Cookie("email")
	if err != nil {
		return false
	}
	em := ck.Value

	ck, err = ct.Request.Cookie("password")
	if err != nil {
		return false
	}
	pwd := ck.Value
	email := ct.GetCookie("email")
	password := ct.GetCookie("password")
	if em == "" || pwd == "" || email == "" || password == "" {
		return false
	}
	return email == em && password == pwd
}
